<script lang="ts" setup name="pet">
import { storeToRefs } from 'pinia'
import { getPetShowApi } from '@/api/index'
import { useWallStore } from '@/store'

definePage({
  style: {
    navigationBarTitleText: '猫狗壁纸乐园',
    enablePullDownRefresh: true,
  },
})
let { petDetail } = storeToRefs(useWallStore())
const petList = reactive([])
const windowHeight = ref(0)
const currenTabs = ref(0)
const showBackTop = ref(false) // 控制返回顶部按钮的显示
const petClass = [
  { name: '全部', type: 'all' },
  { name: '猫', type: 'cat' },
  { name: '狗', type: 'dog' },
]
const petData = reactive({ size: 10, type: 'all' })

function getWallApi() {
  return new Promise((resolve, reject) => {
    getPetShowApi(petData).then((res) => {
      petList.push(...res)
      resolve(res)
    })
  })
}
async function pullDownRefresh(flag: boolean = false) {
  // currenTabs.value =0;
  // petData.type = 'all'
  petList.length = 0
  await getWallApi()
  flag && uni.stopPullDownRefresh()
}
function scrollToTop(flag: boolean) {
  // 滚动到顶部的逻辑
  if (flag) {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    })
    showBackTop.value = !showBackTop.value
  }
}
function tabsHandler(data) {
  console.log(data)

  currenTabs.value = data.index
  petData.type = data.type
  petList.length = 0
  getWallApi()
}
function goPetDetail(item) {
  // 在当前页面的 onLoad 或 onShow 生命周期中调用
  const pages = getCurrentPages() // 获取页面栈
  if (pages.length > 1) {
    const prevPage = pages[pages.length - 2] // 上一个页面对象
    const prevPath = prevPage.route // 上一个页面的路径（不含参数）
    if (prevPath !== 'pages/petDetail/petDetail') {
      petDetail.value = item
      if (item.url) {
        uni.navigateTo({
          url: `/pages/petDetail/petDetail?url=${item.url}`,
        })
      }
    }
    console.log('上一个页面路径:', prevPath) // 输出如：pages/list/list
  }
}
onLoad((options) => {
  if (options.type) {
    uni.setNavigationBarTitle({ title: options.type })
    petData.type = options.type
  }
  // 获取屏幕高度
  uni.getSystemInfo({
    success: (res) => {
      windowHeight.value = res.windowHeight
    },
  })
  getWallApi()
})
onReachBottom(() => {
  getWallApi()
})
onPullDownRefresh(() => {
  pullDownRefresh(true)
})
// 监听页面滚动，动态控制下拉刷新的启用/禁用
onPageScroll((e) => {
  // 滚动超过一个屏幕高度时显示返回顶部按钮
  if (e.scrollTop > windowHeight.value) {
    showBackTop.value = true
  }
  else {
    showBackTop.value = false
  }
})
</script>

<template>
  <view class="demo2">
    <!-- #ifndef MP-WEIXIN -->
    <uv-sticky bg-color="#fff">
      <uv-tabs :list="petClass" :scrollable="false" :current="currenTabs" @click="tabsHandler" />
    </uv-sticky>
    <!-- #endif -->
    <view class="flex flex-col items-center py-10px">
      <view v-for="(pet, index) in petList" :key="index" class="mb-10px mt-10px w-92vw flex flex-col items-center" @click="goPetDetail(pet)">
        <view class="w-full overflow-hidden rounded-lg shadow-md">
          <uv-image :src="pet.url" :observe-lazy-load="true" width="100%" height="40vh" radius="4">
            <template #loading>
              <uv-loading-icon color="#57be6a" />
            </template>
          </uv-image>

          <view class="bg-white p-4">
            <view class="mb-3 text-base text-gray-800">
              {{ pet.content }}
            </view>
            <view class="text-right text-sm text-gray-600">
              {{ pet.author }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-if="showBackTop">
      <view
        class="flash fixed bottom-66px right-20px size-36px flex items-center justify-center rounded-full bg-green-500 shadow-lg"
        @click="pullDownRefresh()"
      >
        <uv-icon name="reload" color="#ffffff" size="18" />
      </view>
      <view
        class="fixed bottom-15vh right-20px size-36px flex items-center justify-center rounded-full bg-green-500 shadow-lg"
        :class="!showBackTop && 'disabled-grew'" @click="scrollToTop(showBackTop)"
      >
        <uv-icon name="arrow-up" color="#ffffff" size="18" />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.disabled-grew {
  background: #c7bdbd;
}
.flash {
  bottom: calc(46px + 15vh);
}
</style>
